<!DOCTYPE html>
<html>
<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
</head>
<style>
.router-link-active{
  background-color: rgb(17, 0, 255);
  color: #fff;
}  
</style>
<body>
<div id="app">
  <router-link tag="button" to="/home">首页</router-link>
  <router-link tag="button" to="/news">新闻页</router-link>
  <router-link tag="button" to="/about">关于我们</router-link>
  <hr>
  <router-view></router-view>
</div>
</body>
<script src="./vue.js"></script>
<script src="./vue-router.js"></script>
<script>
const Login = {
  template:`
    <div>
      <h2>我是登录页</h2>
      <button @click="login">点击登录</button>
    </div>
  `,
  mounted(){
    console.log( this.$route )
  },
  methods:{
    login(){
      setTimeout(()=>{
        const token = 'hgdjadugwdhsh'
        localStorage.setItem("access_token",token)
        this.$route.replace(this.$route.query.from)
      },2000)
    }
  }
}
const Home = {
  niadkktemplate:`
    <div>
      <h2>我是首页</h2>
    </div>
  `
}
const News = {
  template:`
    <div>
      <h2>我是新闻页</h2>
    </div>
  `
}
const About = {
  template:`
    <div>
      <h2>我是关于我们</h2>
    </div>
  `
}
const routes = [
  {
    path: '/',
    redirect: 'home'
  },
  {
    path: '/home',
    component: Home
  },
  {
    path: '/news',
    component: News
  },
  {
    path: '/about',
    component: About
  },
  {
    path: '/login',
    component: Login
  }
]
const router = new VueRouter({
  routes
})
router.beforeEach((to,from,next)=>{
  next()
  if(to.path==='/login'){
    next()
  }else{
    const token = localStorage.getItem('access_token')
    if(token){
      next()
    }else{
      next({
        path: '/login',
        query: {
          from: to.path
        }
      })
    }
  }
})
const vm = new Vue({
  el: '#app',
  router
})
</script>
</html>